using UnityEngine;
using System.Collections;

public class PlaneLooper : MonoBehaviour
{

    private GameObject plane;
    private GameObject character;


    private ArrayList obstacles = new ArrayList();
    private Vector3 initialPlanePositionVector;
    // Use this for initialization
    void Start()
    {
        plane = new GameObject("Ground");
        plane.AddComponent<MeshFilter>().sharedMesh = CreateMesh(0.9f, 15.0f, "Ground");
        plane.AddComponent<BoxCollider>();
        plane.AddComponent<MeshRenderer>().material = new Material(Resources.Load("GoodDirt", typeof(Material)) as Material);
        
        plane.transform.Translate(new Vector3(0, 0, 13));

        initialPlanePositionVector = plane.transform.position;
        character = GameObject.Find("Constructor");
        character.animation.Play("run");

        InstantiateObstacles(obstacles);
    }

    // Update is called once per frame
    void Update()
    {

        if (plane.transform.position.z + 10 < character.transform.position.z - 0.1)
        {
            plane.transform.position = initialPlanePositionVector;
            InstantiateObstacles(obstacles);
        }

        //To be happened in each frame
        float distancePerFrame = Time.deltaTime * 3;
        Vector3 distanceVector = new Vector3(0, 0, -distancePerFrame);
        plane.transform.Translate(distanceVector);

        StartCoroutine("CleanRemovableObstacles");

    }

    //TODO: Obstacles should be distributed randomly 
    void InstantiateObstacles(ArrayList obstacles)
    {
        for (int i = 0; i < 3; i++)
        {
            GameObject obstacle = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            obstacle.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
            obstacle.transform.parent = plane.transform;
            obstacle.AddComponent<Rigidbody>();

            obstacle.rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;

            //obstacle.rigidbody.constraints = RigidbodyConstraints.FreezePosition;


            Vector3 obstacle1PositionVector = new Vector3(plane.transform.position.x + 1f * randomPositionGenerator(), plane.transform.position.y + 3.0f, plane.transform.position.z -4 + 3 * (i + 1));
            obstacle.transform.position = obstacle1PositionVector;

            obstacles.Add(obstacle);

        }
    }

    int randomPositionGenerator()
    {
        return (int)Random.Range(-1.9f, 1.9f);
    }

    IEnumerator CleanRemovableObstacles()
    {
        foreach (GameObject obstacle in obstacles)
        {
            if (obstacle != null && obstacle.transform.position.z + 1 < character.transform.position.z)
            {
                Destroy(obstacle);
            }
        }
       yield return 0;
    }


    Mesh CreateMesh(float width, float height, string name)
    {
        Debug.Log("Create Mesh width: " + width + " height: " + height + " name: " + name);
        Mesh mesh = new Mesh();
        mesh.name = name;
        mesh.vertices = new Vector3[]{new Vector3(-width, 0.01f, -height),
        new Vector3(width, 0.01f, -height),
        new Vector3(width, 0.01f, height),
        new Vector3(-width, 0.01f, height)};

        mesh.uv = new Vector2[] {new Vector2 (0, 0),
        new Vector2 (0, 1),
        new Vector2(1, 1),
        new Vector2 (1, 0) };

        mesh.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        return mesh;
    }
}
